#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tmf_modules.py
@version:
@time: 2022/05/06 
"""
from pprint import pprint

from TapClientCore.T02_tm_api.v2_api.v2_tm import v2tm as TM


class TMFModules:

    @staticmethod
    def _get_api_serve_status():
        return TM.get_worker_by_filter().get('data')

    @staticmethod
    def _get_modules_by_filter(_filter):
        return TM.get_modules_by_filter(_filter).get('data')

    @staticmethod
    def _post_modules(payload):
        return TM.post_modules(payload)

    @staticmethod
    def _patch_modules(payload):
        return TM.patch_modules(payload)

    @staticmethod
    def _delete_modules_by_id(modules_id, table_name):
        return TM.delete_modules_by_id(modules_id, table_name)

    @staticmethod
    def _post_modules_copy_by_id(modules_id, payload):
        return TM.post_modules_copy_by_id(modules_id, payload)

    @staticmethod
    def _get_modules_preview():
        return TM.get_modules_preview()

    @staticmethod
    def _get_modules_rankLists_by_filter(_filter):
        return TM.get_modules_rankLists_by_filter(_filter)

    @staticmethod
    def _get_modules_apiList():
        return TM.get_modules_apiList()

    # 获取api server 状态
    def get_api_serve_status(self):
        response =self._get_api_serve_status()
        return response.get('items')[0]['worker_status']['status']

    def get_rankLists_failRate(self):
        _filter = {
            "where": {
                "type": "failRate"
            },
            "order": "DESC",
        }
        return self._get_modules_rankLists_by_filter(_filter).get('data').get('items')

    def get_rankLists_responseTime(self):
        _filter = {
            "where": {
                "type": "responseTime"
            },
            "order": "DESC",
        }
        return self._get_modules_rankLists_by_filter(_filter).get('data').get('items')

    # 查询API preview
    def get_api_preview(self):
        return self._get_modules_preview()

    # 查询API列表
    def get_modules_apiList(self):
        return self._get_modules_apiList().get('data').get('items')

    # 查询API
    def get_modules_api_server_by_name(self, name):
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "tablename DESC",
                "limit": limit,
                "fields": {
                    "apiVersion": True,
                    "basePath": True,
                    "connection": True,
                    "datasource": True,
                    "description": True,
                    "id": True,
                    "status": True,
                    "tablename": True,
                    "user_id": True,
                    "last_updated": True,
                    "listtags": True,
                    "name": True,
                    "source._id": True,
                    "source.user_id": True
                },
                "skip": skip,
                "where": {
                    "status": "all"
                }
            }
            response = self._get_modules_by_filter(_filter)
            items = response.get('items')
            if items:
                for one in items:
                    if one.get('name') == name:
                        return one
            else:
                from TapUtil.logfunc.logger import logger
                logger.fatal(f'not found {name} api')
                raise
            skip += limit

    # 删除所有API
    def delete_all_api_server(self):
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "tablename DESC",
                "limit": limit,
                "fields": {
                    "apiVersion": True,
                    "basePath": True,
                    "connection": True,
                    "datasource": True,
                    "description": True,
                    "id": True,
                    "status": True,
                    "tablename": True,
                    "user_id": True,
                    "last_updated": True,
                    "listtags": True,
                    "name": True,
                    "source._id": True,
                    "source.user_id": True
                },
                "skip": skip,
                "where": {
                    "status": "all"
                }
            }
            response = self._get_modules_by_filter(_filter)
            items = response.get('items')
            if items:
                for one in items:
                    self._delete_modules_by_id(one.get('id'), one.get('tablename'))
            else:
                from TapUtil.logfunc.logger import logger
                logger.fatal(f'delete all')
                return
            skip += limit

    # 创建__API
    def post_modules_api_server(self, payload):
        """
        tableName = payload.get('tableName')
        apiVersion = payload.get('apiVersion')
        apiName = payload.get('apiName')
        fields = payload.get('fields')
        """
        dataSourceId = payload.get('dataSourceId')
        tableName = payload.get('tableName')
        apiVersion = payload.get('apiVersion')
        apiName = payload.get('apiName')
        fields = payload.get('fields')
        basePath = f'{apiName}_{tableName}'
        _payload = {
            "datasource": dataSourceId,
            "tablename": tableName,
            "readPreference": "",
            "readConcern": "",
            "apiVersion": apiVersion,
            "name": apiName,
            "describtion": "",
            "prefix": "",
            "basePath": basePath,
            "path": f"/api/{apiVersion}/{basePath}",
            "apiType": "defaultApi",
            "status": "pending",
            "createType": "",
            "paths": [
                {
                    "path": f"/api/{apiVersion}/{basePath}",
                    "method": "POST",
                    "description": "创建新记录",
                    "name": "create",
                    "result": "Document",
                    "type": "preset",
                    "acl": [
                        "admin"
                    ]
                },
                {
                    "path": f"/api/{apiVersion}/{basePath}/{id}",
                    "method": "GET",
                    "description": "根据id获取记录",
                    "name": "findById",
                    "params": [
                        {
                            "name": "id",
                            "type": "string",
                            "defaultvalue": 1,
                            "description": "document id"
                        }
                    ],
                    "result": "Document",
                    "type": "preset",
                    "acl": [
                        "admin"
                    ]
                },
                {
                    "path": f"/api/{apiVersion}/{basePath}/{id}",
                    "method": "PATCH",
                    "name": "updateById",
                    "params": [
                        {
                            "name": "id",
                            "type": "string",
                            "defaultvalue": 1,
                            "description": "document id"
                        }
                    ],
                    "description": "根据id更新记录",
                    "result": "Document",
                    "type": "preset",
                    "acl": [
                        "admin"
                    ]
                },
                {
                    "path": f"/api/{apiVersion}/{basePath}/{id}",
                    "method": "DELETE",
                    "name": "deleteById",
                    "params": [
                        {
                            "name": "id",
                            "type": "string",
                            "description": "document id"
                        }
                    ],
                    "description": "根据id删除记录",
                    "type": "preset",
                    "acl": [
                        "admin"
                    ]
                },
                {
                    "path": f"/api/{apiVersion}/{basePath}",
                    "method": "GET",
                    "name": "findPage",
                    "params": [
                        {
                            "name": "page",
                            "type": "int",
                            "defaultvalue": 1,
                            "description": "page number"
                        },
                        {
                            "name": "limit",
                            "type": "int",
                            "defaultvalue": 20,
                            "description": "max records per page"
                        },
                        {
                            "name": "sort",
                            "type": "object",
                            "description": "sort setting,Array ,format like [{'propertyName':'ASC'}]"
                        },
                        {
                            "name": "filter",
                            "type": "object",
                            "description": "search filter object,Array"
                        }
                    ],
                    "description": "分页获取记录",
                    "result": "Page<Document>",
                    "type": "preset",
                    "acl": [
                        "admin"
                    ]
                }
            ],
            "listtags": [],
            "fields": fields
        }
        return self._post_modules(_payload)

    # 创建API
    def create_api_server(self, connection_id, api_name, table_name, fields):
        payload = {
            "dataSourceId": connection_id,
            "tableName": table_name,
            'apiVersion': 'v1',
            'apiName': api_name,
            'fields': fields
        }
        return self.post_modules_api_server(payload)

    # 发布API
    def active_modules_api_server_by_name(self, api_name):
        response = self.get_modules_api_server_by_name(api_name)
        api_id = response.get('id')
        api_table = response.get('tablename')
        payload = {
            "status": "active",
            "id": api_id,
            "tablename": api_table
        }
        self._patch_modules(payload)

    # 取消发布API
    def pending_modules_api_server_by_name(self, api_name):
        response = self.get_modules_api_server_by_name(api_name)
        api_id = response.get('id')
        api_table = response.get('tablename')
        payload = {
            "status": "pending",
            "id": api_id,
            "tablename": api_table
        }
        self._patch_modules(payload)

    # 删除API
    def delete_modules_api_server_by_name(self, api_name):
        response = self.get_modules_api_server_by_name(api_name)
        api_id = response.get('id')
        api_table = response.get('tablename')
        self._delete_modules_by_id(api_id, api_table)


if __name__ == '__main__':
    T = TMFModules()
    res = T.delete_all_api_server()
    pprint(res)
